<template>
  <a-modal
    v-model:visible="visible"
    :width="600"
    title="重置密码"
    :confirm-loading="confirmLoading"
    :afterClose="remove"
    @ok="handleOk"
  >
    <div>
      <schema-form ref="dynamicForm" :form-schema="formSchema" />
    </div>
  </a-modal>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, toRefs } from 'vue'
import { Modal } from 'ant-design-vue'
import { SchemaForm } from '@/components/JSON-schema-form'
import { getFormSchema } from './reset-form-schema'
import { changePassword } from '@/api/system/user'
import md5 from 'blueimp-md5'
/**
 * @description 验证表单
 */
export default defineComponent({
  name: 'RuleForm',
  components: { SchemaForm, [Modal.name]: Modal },
  props: {
    remove: {
      // 移除模态框
      type: Function
    },
    fields: {
      type: Object,
      default: () => ({})
    },
    callback: {
      type: Function
    }
  },
  setup(props) {
    const dynamicForm = ref<InstanceType<typeof SchemaForm>>()

    const state = reactive({
      visible: true,
      confirmLoading: false,
      spinning: false,
    })
    const handleOk = (e) => {
      e.preventDefault()
      dynamicForm.value?.validate().then(async () => {
        state.confirmLoading = true
        try {
          const params = {
            password: md5(dynamicForm.value?.modelRef['password']),
            confirmPassword: md5(dynamicForm.value?.modelRef['confirmPassword'])
          }
          await changePassword(Object.assign(params, { id: props.fields.userId ? props.fields.userId : props.fields.id })).finally(
            () => (state.confirmLoading = false)
          )
          state.visible = false
          props?.callback?.()
        } catch (error) {
          console.log('error', error)
          state.confirmLoading = false
        }
      })
    }


    return {
      ...toRefs(state),
      dynamicForm,
      confirm,
      formSchema: getFormSchema(dynamicForm),
      handleOk
    }
  }
})
</script>

<style lang="scss" scoped>
.btn-rows {
  button {
    margin-right: 12px;
  }
}
</style>
